﻿using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.SceneManagement;

/// <summary>
/// UI管理器
/// </summary>
public class UIManager : Singleton<UIManager> {

    Transform canvas;
    Camera uiCamera;

    public Camera UICamera { get { return uiCamera; } }
    public Transform Canvas { get { return canvas; } }

    Dictionary<string, GameObject> dic = new Dictionary<string, GameObject>();

    private bool _inLoadingS;
    private string _sceneName;
    private object[] _sceneParams;

    public override void Init()
    {
        canvas = GameObject.Find("Canvas").transform;
        uiCamera = Camera.main.GetComponent<Camera>();
    }

    public GameObject Open<T>(params object[] args) where T:UIBase
    {
        string panelName = typeof(T).Name;//获取泛型名字

        GameObject panel;
        if(dic.ContainsKey(panelName))
        {
            panel = dic[panelName];
            panel.SetActive(true);
        }
        else
        {
            var prefab = Resources.Load<GameObject>("GUI/" + panelName);
            panel = GameObject.Instantiate(prefab, canvas);
            dic.Add(panelName, panel);
        }

        panel.transform.SetAsLastSibling();//设置新页面在最前方
        UIBase ui = panel.GetComponent<UIBase>();
        if(ui) ui.Init(args);
        
        return panel;
    }

    public void GoScene(string sceneName, params object[] options)
    {
        if (!_inLoadingS)
        {
            _inLoadingS = true;
            _sceneName = sceneName;
            _sceneParams = options;

            SceneManager.LoadSceneAsync("Loading");
        }
    }

    public void Close<T>(bool destroy = false) where T : UIBase
    {
        string panelName = typeof(T).Name;

        if (dic.ContainsKey(panelName))
        {
            GameObject panel = dic[panelName];
            panel.GetComponent<UIBase>().OnClose();

            if (destroy)
            {
                GameObject.Destroy(panel);
                dic.Remove(panelName);
            }
            else
            {
                panel.SetActive(false);
            }
        }
        else
            Debug.Log(panelName + "页面不存在");
    }

    public T GetPanel<T>() where T:UIBase
    {
        string panelName = typeof(T).Name;
        if(dic.ContainsKey(panelName))
        {
            return dic[panelName].GetComponent<T>();
        }
        return null;
    }
}
